﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using System;

namespace Core.FrameWork.Commons.App
{
    /// <summary>
    /// 全局应用类
    /// </summary>
    public class AppCenter
    {
        /// <summary>
        /// 路径
        /// </summary>
        public static Microsoft.AspNetCore.Hosting.IWebHostEnvironment webHostEnvironment;

        /// <summary>
        /// 全局配置选项
        /// </summary>
        public static Microsoft.Extensions.Configuration.IConfiguration Configuration;

        /// <summary>
        ///  应用服务
        /// </summary>
        public static IServiceCollection Services;

        /// <summary>
        /// 服务提供器
        /// </summary>
        public static IServiceProvider ServiceProvider => HttpContext?.RequestServices ?? Services.BuildServiceProvider();

        /// <summary>
        /// 获取请求上下文
        /// </summary>
        public static HttpContext? HttpContext => HttpContextLocal.Current();
        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <returns></returns>
        public static TService GetService<TService>()
            where TService : class
        {
            return GetService(typeof(TService)) as TService ?? throw new Exception($"没有类型为：【{nameof(Type)}】实例");
        }

        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object GetService(Type type)
        {
            return ServiceProvider.GetService(type) ?? throw new Exception($"没有类型为：【{nameof(type)}】实例");
        }

        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <typeparam name="TService"></typeparam>
        /// <returns></returns>
        public static TService GetRequiredService<TService>()
            where TService : class
        {
            return GetRequiredService(typeof(TService)) as TService ?? throw new Exception($"没有类型为：【{nameof(TService)}】实例");
        }

        /// <summary>
        /// 获取请求生命周期的服务
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object GetRequiredService(Type type)
        {
            return ServiceProvider.GetRequiredService(type);
        }
    }
}
